# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: socket_test.py
Author: kij
Create Date: 2021/2/28
-------------------------------------------------
"""
import struct
# 粘包练习
# 约定收发规则 先发送字段长度
# struct模块专门打包
# 将199转化成四个字节
# v1 = struct.pack('i',1999999999)
# # 将四个字节的199转化成整型
# v2 = struct.unpack('i',v1)
# print(v1)
# print(v2)
# 发送的时候吧字节长度加在最前面
import socket


def read_file(conn, read_size=1024):
	bytes_list = []
	has_read_size = 0
	while has_read_size < 4:
		check = conn.recv(4 - has_read_size)
		has_read_size += len(check)
		bytes_list.append(check)
	header = b''.join(bytes_list)
	next_size = struct.unpack('i', header)[0]
	print("接下来将要读取的数据长度=======%a" %next_size)
	all_read_size = 0
	files_byte = []
	while all_read_size < next_size:
		# reads_size = read_size if next_size-all_read_size>read_size else next_size-all_read_size
		if next_size - all_read_size > read_size:
			reads_size = read_size
		else:
			reads_size = next_size - all_read_size
		print("循环中将要读取的字节长度===%s" %reads_size)
		bytes_file = conn.recv(reads_size)
		print("循环读出的数据长度===%s" %len(bytes_file))
		files_byte.append(bytes_file)
		all_read_size += len(bytes_file)
		print("循环中已读取的字节长度=============%s" % all_read_size)
	my_message = b''.join(files_byte)
	print(len(my_message))
	# print(my_message)
	print(my_message.decode('utf-8'))
	return None


def run():
	print("""
		上传文件还是文本
		msg|文本内容
		file|文件路径
		""")
	# 新建socket对象
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	# 绑定端口和ip 元组类型端口为整型
	sock.bind(('192.168.1.27', 9997))
	# 设置最大连接数
	sock.listen(5)
	# 开始链接客户端
	conn, addr = sock.accept()
	print("addr=", addr)
	print("conn=", conn)
	read_file(conn)
	read_file(conn)


if __name__ == "__main__":
	run()
